#include "delay.h"


volatile unsigned long current_time=0x00000000;

void __attribute__((__interrupt__, __shadow__)) _T1Interrupt(void)
{
current_time++;
IFS0bits.T1IF = 0; //Reset Timer1 interrupt flag and Return from ISR
}


void DELAY_5MS(void){
	volatile unsigned int r1=0x00;
	while (r1<0x999){
	r1++;
	}
}

void DELAY_40MS(void){ //120ms
	volatile unsigned int r2=0x00;
	while (r2<0xFFFF){ //15MS=0x1CCB
	r2++;
	}
}

void DELAY_MS(unsigned int b){
	volatile unsigned int r3=0x00;
	b=b*0x1EB;
	while (r3<b){
	r3++;
	}
}

void DELAY_40US(void){
	volatile unsigned int r4=0x00;
	while (r4<0x1A){ //0x15=40us-0x1A=50us=2us per clck
	r4++;
	}
}

void DELAY_100US(void){
	volatile unsigned int r5=0x00;
	while (r5<0x39){ //0x34=100us-0x39=100us
	r5++;
	}
}

void DELAY_LED(void){//tijdelijk voor flikkeren van ledjes
	DELAY_40MS();
	DELAY_40MS();
}

unsigned long GetTime(void){
	return current_time;	
}

unsigned long GetTimeDifference( unsigned long time)
{
	return GetTime() - time;
}

void InitTimer1(void){
	//pic family reference manual (timers): http://ww1.microchip.com/downloads/en/DeviceDoc/39704a.pdf
	/* The following code example will enable Timer1 interrupts, load the Timer1
	Period register and start Timer1.
	When a Timer1 period match interrupt occurs, the interrupt service
	routine must clear the Timer1 interrupt status flag in software.
	*/
	T1CON 			= 0x00; 	//Stops the Timer1 and reset control reg.
	TMR1 			= 0x00; 	//Clear contents of the timer register
	PR1 			= 58;		//Load the Period register with the value 29
	T1CONbits.TCKPS = 0b10;		//prescaler 1:256
	IPC0bits.T1IP 	= 0x01; 	//Setup Timer1 interrupt for desired priority level
	// (This example assigns level 1 priority)
	IFS0bits.T1IF 	= 0; 		//Clear the Timer1 interrupt status flag
	IEC0bits.T1IE 	= 1; 		//Enable Timer1 interrupts
	T1CONbits.TON 	= 1; 		//Start Timer1 with clock source set to Fosc/2(=4mhz)
}
	
